<script setup lang="ts">
import useStatusBarHeight from '@/composables/statusBarHeight'
import { useGeneralDataStore } from '@/store/generalData'
import { useUserInfoStore } from '@/store/userInfo'
import { withDomain } from '@/utils/withDomain'
import { useRouterGuards } from '@/composables/useRouterGuards'
import { fetchCouponModalListAPI } from '@/apis/fetchCouponModalList'

const router = useRouter()
const routerGuards = useRouterGuards()
const userInfoStore = useUserInfoStore()
const generalDataStore = useGeneralDataStore()

const statusBarHeight = useStatusBarHeight()
const topPadding = computed(() => statusBarHeight.value + uni.upx2px(88) + uni.upx2px(20))

// 是否显示状态栏背景
const isShowNavBg = ref(false)
// 监听页面滚动，更新状态栏背景可见性
onPageScroll((e) => {
  const toggle = useThrottleFn(() => isShowNavBg.value = e.scrollTop > 16, 100)
  toggle()
})
// 将状态栏背景可见性提供给状态栏组件
provide(isShowNavigationBarBackgroundKey, isShowNavBg)

/* -------------------------------- 搜索 START -------------------------------- */
const searchText = ref('')

function handleConfirmSearch() {
  routerGuards(() => {
    router.push({
      name: 'searchResult',
      params: { keyword: searchText.value },
    })
  })
  searchText.value = ''
}
/* --------------------------------- 搜索 END --------------------------------- */

/* -------------------------------- 轮播图 START ------------------------------- */
const current = ref(0)
/* --------------------------------- 轮播图 END -------------------------------- */

/* ------------------------------- 优惠券弹窗 START ------------------------------ */
const isShowCouponModal = ref(false)
const newCustomerCouponList = ref<Coupon[]>([])

onLoad(async () => {
  if (userInfoStore.userInfo?.token) {
    isShowCouponModal.value = userInfoStore.userInfo.login_times === 1

    const res = await fetchCouponModalListAPI(userInfoStore.userInfo.token)
    if (res.data?.code === 1)
      newCustomerCouponList.value = res.data.data
    else
      uni.showToast({ title: res.data?.msg, icon: 'none' })

    // 每登录一次 login time 加 1
    userInfoStore.setUserInfo({
      ...userInfoStore.userInfo,
      login_times: userInfoStore.userInfo.login_times + 1,
    })
  }
})

onShow(() => generalDataStore.update())

function handleTapCouponModalCloseButton() {
  uni.setStorageSync('hasShownPopup', true)
  isShowCouponModal.value = false
}
/* -------------------------------- 优惠券弹窗 END ------------------------------- */

function handleTapNotice() {
  routerGuards(() => {
    router.push('notice')
  })
}

function handleTapAppointmentCard() {
  routerGuards(() => {
    router.push('appointment')
  })
}

function handleTapRecordCard() {
  routerGuards(() => {
    router.push('record')
  })
}

function handleTapPointsMallCard() {
  routerGuards(() => {
    router.push('pointsMall')
  })
}

function handleTapCouponListCard() {
  routerGuards(() => {
    router.push({
      name: 'couponList',
      params: { type: '领券中心' },
    })
  })
}

function handleTapProjectCard(id: string) {
  routerGuards(() => {
    router.push({
      name: 'projectDetail',
      params: { id },
    })
  })
}
</script>

<template>
  <view class="absolute left-0 top-0 h-364rpx w-screen from-#4999F7 to-#78D9FE bg-gradient-to-br" />
  <NavigationBar front-color="#ffffff">
    <view class="absolute left-20rpx top-50% -transform-translate-y-50%">
      <uv-search
        v-model="searchText"
        shape="round" :bg-color="isShowNavBg ? '#F8F8F8' : '#FFFFFF'" color="#333333" search-icon-size="48rpx"
        search-icon-color="#9A9A9A" placeholder-color="#999999" :show-action="false"
        height="58rpx" placeholder="请输入服务项目"
        :box-style="{ padding: '0 4rpx 0 16rpx' }"
        :custom-style="{ width: '530rpx' }"
      >
        <template #suffix>
          <button class="h-52rpx w-106rpx flex items-center justify-center rounded-full from-#77DAFE to-#4999F7 bg-gradient-to-l text-30rpx text-white font-medium" @tap="handleConfirmSearch">
            搜索
          </button>
        </template>
      </uv-search>
    </view>
  </NavigationBar>
  <Spacer :height="topPadding" unit="px" />
  <view class="relative z-1 rounded-t-40rpx bg-#F8F8F8 px-30rpx py-32rpx" :style="{ minHeight: `calc(100vh - ${topPadding}px)` }">
    <view class="absolute left-0 top-0 h-80vh from-#FFFFFF to-#F8F8F8 bg-gradient-to-b" />
    <!-- 轮播图 START -->
    <uv-swiper
      :list="generalDataStore.generalData?.nav.map((item) => withDomain(item.image))"
      height="182rpx"
      radius="12rpx"
      @change="(e: any) => current = e.current"
    />
    <!-- 轮播图 END -->
    <Spacer height="32" />
    <!-- 公告 START -->
    <view class="flex items-center justify-between rounded-12rpx bg-#4999F7 bg-opacity-20 px-20rpx py-15rpx" @tap="handleTapNotice">
      <view class="flex items-center">
        <image class="h-39rpx w-46rpx flex-shrink-0" src="@/static/images/home/notice.png" />
        <Spacer width="4" />
        <view class="flex-shrink-0 rounded-6rpx bg-#4999F7 p-6rpx text-28rpx text-white font-bold leading-28rpx">
          公告
        </view>
        <uv-notice-bar
          :text="generalDataStore.generalData?.notice.title || ''"
          :icon="false"
          font-size="14rpx"
          color="rgb(51, 51, 51)"
          bg-color="rgba(0, 0, 0, 0)"
          :custom-style="{ width: '400rpx', paddingTop: 0, paddingBottom: 0 }"
        />
      </view>
      <view class="flex-shrink-0 text-24rpx text-#333333 font-medium leading-24rpx">
        更多消息>
      </view>
    </view>
    <!-- 公告 END -->
    <Spacer height="32" />
    <!-- 网格 START -->
    <view class="grid grid-cols-2 gap-30rpx">
      <!-- 1 -->
      <view class="relative h-180rpx w-330rpx px-28rpx pb-32rpx pt-44rpx" @tap="handleTapAppointmentCard">
        <image class="absolute left-0 top-0 z-0 h-180rpx w-330rpx" src="@/static/images/home/grid_0.png" />
        <view class="relative z-1 text-32rpx text-#AD480D font-bold leading-32rpx">
          预约就诊
        </view>
        <Spacer height="28" />
        <button class="relative z-1 inline rounded-full from-#FE6714 to-#EC9E48 bg-gradient-to-l p-12rpx text-24rpx text-white font-medium leading-24rpx">
          立即预约
        </button>
      </view>
      <!-- 2 -->
      <view class="relative h-180rpx w-330rpx px-28rpx pb-32rpx pt-44rpx" @tap="handleTapRecordCard">
        <image class="absolute left-0 top-0 z-0 h-180rpx w-330rpx" src="@/static/images/home/grid_1.png" />
        <view class="relative z-1 text-32rpx text-#2F72AF font-bold leading-32rpx">
          就诊记录
        </view>
        <Spacer height="28" />
        <button class="relative z-1 inline rounded-full from-#398AE3 to-#62B2EC bg-gradient-to-l p-12rpx text-24rpx text-white font-medium leading-24rpx">
          立即查看
        </button>
      </view>
      <!-- 3 -->
      <view class="relative h-180rpx w-330rpx px-28rpx pb-32rpx pt-44rpx" @tap="handleTapPointsMallCard">
        <image class="absolute left-0 top-0 z-0 h-180rpx w-330rpx" src="@/static/images/home/grid_2.png" />
        <view class="relative z-1 text-32rpx text-#6A6CCB font-bold leading-32rpx">
          积分商城
        </view>
        <Spacer height="28" />
        <button class="relative z-1 inline rounded-full from-#8EA7EB to-#5A55F5 bg-gradient-to-l p-12rpx text-24rpx text-white font-medium leading-24rpx">
          立即兑换
        </button>
      </view>
      <!-- 4 -->
      <view class="relative h-180rpx w-330rpx px-28rpx pb-32rpx pt-44rpx" @tap="handleTapCouponListCard">
        <image class="absolute left-0 top-0 z-0 h-180rpx w-330rpx" src="@/static/images/home/grid_3.png" />
        <view class="relative z-1 text-32rpx text-#AE3037 font-bold leading-32rpx">
          领券中心
        </view>
        <Spacer height="28" />
        <button class="relative z-1 inline rounded-full from-#FA575E to-#F6896D bg-gradient-to-l p-12rpx text-24rpx text-white font-medium leading-24rpx">
          立即领取
        </button>
      </view>
    </view>
    <!-- 网格 END -->
    <Spacer height="40" />
    <!-- 列表标题 START -->
    <Title>推荐服务项目</Title>
    <!-- 列表标题 END -->
    <Spacer height="36" />
    <!-- 列表 Item START -->
    <ProjectItem
      v-for="project in generalDataStore.generalData?.server_project"
      :key="project.id"
      :picture="project.image"
      :title="project.title"
      :price="project.price"
      @tap="handleTapProjectCard(project.id.toString())"
    />
    <!-- 列表 Item END -->
  </view>
  <uv-overlay :show="isShowCouponModal" @tap="handleTapCouponModalCloseButton">
    <uv-transition mode="zoom-in" :show="isShowCouponModal">
      <view class="relative h-screen w-screen">
        <CouponModal
          window-title="新人专享券"
          :period="{ start: newCustomerCouponList[0]?.validate_start_time || '未知', end: newCustomerCouponList[0]?.validate_end_time || '未知' }"
          :coupon-list="newCustomerCouponList"
          @cancel="handleTapCouponModalCloseButton"
        />
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'home'
style:
  navigationStyle: 'custom'
layout: 'custom'
</route>
